package com.commerce.user.controller;

import com.commerce.common.utils.Result;
import com.commerce.user.entity.Permission;
import com.commerce.user.entity.Role;
import com.commerce.user.entity.RolePermission;
import com.commerce.user.entity.UserRole;
import com.commerce.user.mapper.PermissionMapper;
import com.commerce.user.mapper.RoleMapper;
import com.commerce.user.mapper.RolePermissionMapper;
import com.commerce.user.mapper.UserRoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/init")
public class InitController {

    @Autowired
    private RoleMapper roleMapper;
    
    @Autowired
    private PermissionMapper permissionMapper;
    
    @Autowired
    private RolePermissionMapper rolePermissionMapper;
    
    @Autowired
    private UserRoleMapper userRoleMapper;

    /**
     * 初始化角色和权限数据
     */
    @GetMapping("/data")
    public Result<String> initData() {
        try {
            log.info("开始初始化角色和权限数据");
            
            // 检查角色表是否有数据
            if (roleMapper.selectCount(null) == 0) {
                log.info("初始化角色数据");
                
                // 创建管理员角色
                Role adminRole = new Role();
                adminRole.setRoleName("admin");
                adminRole.setDescription("系统管理员");
                adminRole.setCreateTime(LocalDateTime.now());
                adminRole.setUpdateTime(LocalDateTime.now());
                roleMapper.insert(adminRole);
                
                // 创建普通用户角色
                Role userRole = new Role();
                userRole.setRoleName("user");
                userRole.setDescription("普通用户");
                userRole.setCreateTime(LocalDateTime.now());
                userRole.setUpdateTime(LocalDateTime.now());
                roleMapper.insert(userRole);
                
                log.info("角色数据初始化完成");
            }
            
            // 检查权限表是否有数据
            if (permissionMapper.selectCount(null) == 0) {
                log.info("初始化权限数据");
                
                List<Permission> permissions = new ArrayList<>();
                
                // 创建用户管理权限
                Permission userPermission = new Permission();
                userPermission.setPermissionName("用户管理");
                userPermission.setPermissionKey("sys:user");
                userPermission.setDescription("用户管理权限");
                userPermission.setCreateTime(LocalDateTime.now());
                userPermission.setUpdateTime(LocalDateTime.now());
                permissions.add(userPermission);
                
                // 创建商品管理权限
                Permission productPermission = new Permission();
                productPermission.setPermissionName("商品管理");
                productPermission.setPermissionKey("sys:product");
                productPermission.setDescription("商品管理权限");
                productPermission.setCreateTime(LocalDateTime.now());
                productPermission.setUpdateTime(LocalDateTime.now());
                permissions.add(productPermission);
                
                // 创建订单管理权限
                Permission orderPermission = new Permission();
                orderPermission.setPermissionName("订单管理");
                orderPermission.setPermissionKey("sys:order");
                orderPermission.setDescription("订单管理权限");
                orderPermission.setCreateTime(LocalDateTime.now());
                orderPermission.setUpdateTime(LocalDateTime.now());
                permissions.add(orderPermission);
                
                // 创建评论管理权限
                Permission reviewPermission = new Permission();
                reviewPermission.setPermissionName("评论管理");
                reviewPermission.setPermissionKey("sys:review");
                reviewPermission.setDescription("评论管理权限");
                reviewPermission.setCreateTime(LocalDateTime.now());
                reviewPermission.setUpdateTime(LocalDateTime.now());
                permissions.add(reviewPermission);
                
                // 创建系统设置权限
                Permission settingPermission = new Permission();
                settingPermission.setPermissionName("系统设置");
                settingPermission.setPermissionKey("sys:setting");
                settingPermission.setDescription("系统设置权限");
                settingPermission.setCreateTime(LocalDateTime.now());
                settingPermission.setUpdateTime(LocalDateTime.now());
                permissions.add(settingPermission);
                
                // 批量插入权限
                for (Permission permission : permissions) {
                    permissionMapper.insert(permission);
                }
                
                log.info("权限数据初始化完成");
            }
            
            // 检查角色权限关联表是否有数据
            if (rolePermissionMapper.selectCount(null) == 0) {
                log.info("初始化角色权限关联数据");
                
                // 获取所有角色
                List<Role> roles = roleMapper.selectList(null);
                Role adminRole = null;
                Role userRole = null;
                
                for (Role role : roles) {
                    if ("admin".equals(role.getRoleName())) {
                        adminRole = role;
                    } else if ("user".equals(role.getRoleName())) {
                        userRole = role;
                    }
                }
                
                // 获取所有权限
                List<Permission> permissions = permissionMapper.selectList(null);
                
                // 为管理员角色分配所有权限
                if (adminRole != null) {
                    for (Permission permission : permissions) {
                        RolePermission rolePermission = new RolePermission();
                        rolePermission.setRoleId(adminRole.getId());
                        rolePermission.setPermissionId(permission.getId());
                        rolePermission.setCreateTime(LocalDateTime.now());
                        rolePermissionMapper.insert(rolePermission);
                    }
                }
                
                // 为普通用户角色分配基本权限
                if (userRole != null) {
                    for (Permission permission : permissions) {
                        if ("sys:order".equals(permission.getPermissionKey()) || 
                            "sys:review".equals(permission.getPermissionKey())) {
                            RolePermission rolePermission = new RolePermission();
                            rolePermission.setRoleId(userRole.getId());
                            rolePermission.setPermissionId(permission.getId());
                            rolePermission.setCreateTime(LocalDateTime.now());
                            rolePermissionMapper.insert(rolePermission);
                        }
                    }
                }
                
                log.info("角色权限关联数据初始化完成");
            }
            
            // 检查是否需要为用户ID为1的用户分配角色（假设ID为1的是管理员）
            if (userRoleMapper.selectCount(null) == 0) {
                log.info("为默认用户分配角色");
                
                // 获取管理员角色
                List<Role> roles = roleMapper.selectList(null);
                Role adminRole = null;
                
                for (Role role : roles) {
                    if ("admin".equals(role.getRoleName())) {
                        adminRole = role;
                        break;
                    }
                }
                
                if (adminRole != null) {
                    UserRole userRole = new UserRole();
                    userRole.setUserId(1L); // 假设ID为1的是管理员用户
                    userRole.setRoleId(adminRole.getId());
                    userRole.setCreateTime(LocalDateTime.now());
                    userRoleMapper.insert(userRole);
                    
                    log.info("为用户ID=1分配了管理员角色");
                }
            }
            
            return Result.success("数据初始化成功");
        } catch (Exception e) {
            log.error("数据初始化失败", e);
            return Result.error("数据初始化失败：" + e.getMessage());
        }
    }
} 